import Vue from 'vue'
import Vuex from 'vuex'

Vue.use(Vuex)
import {
  setToken,
  removeToken
} from '../util/validate'
import {
  home,
  commonRequest,
  postRequest
} from "../api/api.js"

export const state = () => ({
  selectAddress: null,
  token: "",
  userInfo: {
    nickName: '',
    avatar: ''
  },
  backName: "",
  isShow: false,
  cityInfo: {},
  getHome: false,
  provinceName: '',
  cityName: '',
  honorAddress: {
    province: '',
    city: '',
    area: ''
  }
})

export const mutations = {
  setSelectAddress(state, payload) {
    state.selectAddress = payload
  },
  setToken(state, token) {
    state.token = token
    setToken(token)
  },
  setUserInfo(state, userInfo) {
    state.userInfo = userInfo
  },
  setBackName(state, backName) {
    state.backName = backName
  },
  setIsShow(state, isShow) {
    state.isShow = isShow
  },
  setIsShowError(state, cityInfo) {
    state.cityInfo = cityInfo
  },
  setHome(state, getHome) {
    state.getHome = getHome
  },
  setProvince(state, provinceName) {
    state.provinceName = provinceName
  },
  setCity(state, cityName) {
    state.cityName = cityName
  },
  setHonorAddress(state, honorAddress) {
    state.honorAddress = honorAddress
  }
}

export const actions = {
  getCityNameError({
    commit
  }) {
    // commonRequest('/api/sys/depart/getSubInfo', {})
    return new Promise(() => {
      commonRequest("/api/sys/depart/getSubInfo", {}).then(res => {
        commit('setIsShowError', res.result)
      })
    })
  },
  // 绑定手机号
  bindMobilePhoneNumber({
    commit,
    dispatch
  }, url) {
    return new Promise(((resolve, reject) => {
      postRequest(url).then(res => {
        if (res.code === 200) {
          commit('setToken', res.message)
          setToken(res.message)
          localStorage.setItem('saasToken', res.message)
          dispatch("getUserInfo")
            .then(res => {
              if (!res) {
                resolve()
              } else {
                resolve(res)
              }
            }).catch(error => {
              reject(error)
            })
        } else {
          resolve(res)
          setTimeout(async () => {
            this.$router.push('/');
          }, 1000)
        }
      })
    }))
  },
  //openId登录
  hanldOpenIdLogin({
    commit,
    dispatch
  }, data) {
    return new Promise((resolve, reject) => {
      postRequest("/api/byOpenIdLogin", data).then(res => {
        if (res.code == 200) {
          commit('setToken', res.message)
          setToken(res.message)
          localStorage.setItem('saasToken', res.message)
          dispatch("getUserInfo")
            .then(res => {
              if (!res) {
                resolve()
              } else {
                resolve(res)
              }
            }).catch(error => {
              reject(error)
            })
        } else if (res.code === 10009) {
          resolve(res)
          setTimeout(async () => {
            this.$router.replace({
              path: '/blankPage',
              name: "blankPage"
            })
          }, 1000)
        } else if (res.code === 10010) {
          resolve(res)
          setTimeout(async () => {
            this.$router.push('/bindPhoneNumber')
          }, 1000)
        } else {
          resolve(res)
        }
      })
    })
  },
  // 验证码登录
  hanldCodeLogin({
    commit,
    dispatch
  }, data) {
    return new Promise((resolve, reject) => {
      postRequest("/api/codeLogin", data).then(res => {
        if (res.code == 200) {
          commit('setToken', res.message)
          setToken(res.message)
          localStorage.setItem('saasToken', res.message)
          dispatch("getUserInfo")
            .then(res => {
              if (!res) {
                resolve()
              } else {
                resolve(res)
              }
            }).catch(error => {
              reject(error)
            })
        } else {
          resolve(res)
        }
      })
    })
  },
  handleLogin({
    commit,
    dispatch
  }, data) {
    return new Promise((resolve, reject) => {
      home(data).then(res => {
        // console.log('hehehehehe', res)
        if (res.code === 200) {
          commit('setToken', res.message)
          localStorage.setItem('saasToken', res.message)
          dispatch('getUserInfo').then((res) => {
            if (!res) {
              resolve()
            } else {
              resolve(res)
            }
          })
        } else {
          resolve(res.message)
        }
      }).catch(error => {
        reject(error)
      })
    })
  },
  /* 获取用户信息 */
  getUserInfo({
    commit
  }) {
    return new Promise((resolve, reject) => {
      commonRequest("/api/userInfo").then(res => {
        // console.log(res)
        if (res.code == 10001) {
          localStorage.removeItem('endTime')

        } else if (!res.code) {
          commit('setUserInfo', res.result)
          localStorage.setItem('userInfo', JSON.stringify(res.result))
          resolve()
        } else {
          resolve(res.message)
        }

      }).catch(error => {
        reject(error)
      })
    })
  },
  /* 登出 */
  handleLogout({
    commit
  }) {
    removeToken()
    commit('setToken', '')
    commit('setUserInfo', {
      nickName: '',
      avatar: ''
    })
    localStorage.removeItem('endTime')
    localStorage.removeItem('saasToken')
    localStorage.removeItem('userInfo')
  }
}
